package exquery

import exquery.util.CommonUtil
import exquery.util.FormatQueryResultUtil
import exquery.util.ValidationUtil
import org.apache.log4j.Logger
import org.codehaus.groovy.grails.commons.ConfigurationHolder

class QueryController {

    Logger gLogger = Logger.getLogger(QueryController.class)
    def lookupService
    // Export service provided by Export plugin
    def exportService

    def index = {
        redirect(actionName:'samples_search',controller: 'query')
    }

    def samples_search={
      gLogger.info "Coming into samples_search action of QueryController"

      //def sxObjectType = [[ID:"sample",VALUE:"Sample"],[ID:"classes",VALUE:"Classes"],[ID:"experiments",VALUE:"Experiments"],[ID:"chromatof",VALUE:"Chromatof"]]
      def sxObjectType = CommonUtil.getInstance().getSXObjectType();

      if (session.getAttribute("txtIds") != null) {
        def txtIds = session.getAttribute("txtIds").toString()
        params.setProperty "txtIds",txtIds
      }

      gLogger.info "Out from samples_search action of QueryController"
      return [params:params,sxObjectType:sxObjectType]
    }

    def samples_result={
      gLogger.info "Coming into samples_search action of QueryController"

      def txtIds = ""
      def rdType = params.rdType
      gLogger.info txtIds
      gLogger.info rdType

      if (params.txtIds != null) {
        txtIds = params.txtIds
        session.setAttribute("txtIds", txtIds);
      }
      else {
        txtIds = session.getAttribute("txtIds").toString()
      }

      if(txtIds==null || txtIds.toString().trim().length()==0){
        flash.message = "Error! Ids parameter is mandatory, Please Enter some ids."
        redirect(action: "samples_search",params:[rdType:rdType])
        return
      }
      if(rdType==null || rdType.toString().trim().length()==0){
        flash.message = "Error! Type parameter is mandatory, Please select one type."
        redirect(action: "samples_search",params:[rdType:rdType])
        return
      }

      def ids = CommonUtil.getInstance().prepareSearchableIdList(txtIds)

      def res = []
      if(rdType!=null){
        def idList = []
        if(rdType.toString().equalsIgnoreCase("samples")) {
          ids.each {id->
            if(ValidationUtil.getInstance().isLong(id.toString().trim())){
              idList.add Long.parseLong(id.toString().trim())
            }
          }
          gLogger.info idList
          if( idList.size() > 0 )
          {
            res = lookupService.getSamplesById(idList,params)
          }
          gLogger.info res
        }else if(rdType.toString().equalsIgnoreCase("classes")) {
          ids.each {id->
            if(ValidationUtil.getInstance().isLong(id.toString().trim())){
              idList.add Long.parseLong(id.toString().trim())
            }
          }
          if( idList.size() > 0 )
          {
            res = lookupService.getClassesById(idList,params)
          }
          //gLogger.info res
        }else if(rdType.toString().equalsIgnoreCase("experiments")) {
          ids.each{id->
            if(ValidationUtil.getInstance().isLong(id.toString().trim())){
              idList.add Long.parseLong(id.toString().trim())
            }
          }
          if( idList.size() > 0 )
          {
            res = lookupService.getExperimentsById(idList,params)
          }
          //gLogger.info res
        }else if(rdType.toString().equalsIgnoreCase("chromatofs")) {
          ids.each{id->
            if(id.toString().trim().length()>0){
              idList.add id.toString().trim()
            }
          }

          if( idList.size() > 0 )
          {
            res = lookupService.getChromatofsByFileId(idList,params)
          }
          //gLogger.info res
        } 
      }

      def resultData = null
      def isExport = false
      if(params?.format && params.format != "html"){
        isExport = true
      }

      if(rdType!=null){
        if(rdType.toString().equalsIgnoreCase("samples")) {
          resultData = FormatQueryResultUtil.getInstance().prepareQuerySamplesBySampleIdResult(ids,res,params,isExport)
        }else if(rdType.toString().equalsIgnoreCase("classes")) {
          resultData = FormatQueryResultUtil.getInstance().prepareQuerySamplesByClassIdResult(ids,res,params,isExport)
        } else if(rdType.toString().equalsIgnoreCase("experiments")) {
          resultData = FormatQueryResultUtil.getInstance().prepareQuerySamplesByExperimentIdResult(ids,res,params,isExport)
        } else if(rdType.toString().equalsIgnoreCase("chromatofs")) {
          resultData = FormatQueryResultUtil.getInstance().prepareQuerySamplesByChromatofFileIdsResult(ids,res,params,isExport)
        }
      }


      // Export Result
      if(params?.format && params.format != "html"){
        response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
        response.setHeader("Content-disposition", "attachment; filename=SampleResult.${params.extension}")
        exportService.export(params.format, response.outputStream, resultData.resultList, resultData.fieldList, resultData.labelMap, resultData.formatters, resultData.parameters)
      }else{

      }
      resultData?.putAt "isPaginate",false
      resultData?.putAt "TotalRecordCount",resultData?.resultList?.size()

      gLogger.info "Out from samples_search action of QueryController"
      return [result: resultData,params:params]
    }

    
}
